<template>
  <page-wrap
    hideTab
    back
    title="案例列表"
    stayStill
    bgColor="linear-gradient(360deg, #F7F8FA 0%, #FFE9E0 100%);"
  >
    <view class="library">
      <view class="library-top" :style="'top:' + navHeight + 'px;'">
        <view class="search">
          <u-search
            placeholder="搜索您感兴趣的内容"
            class="library-u-search"
            v-model="keyword"
            height="80"
            bg-color="#ffffff"
            :search-icon="searchIcon"
            :show-action="keyword"
            @search="handleSearch"
            @custom="handleSearch"
          ></u-search>
          <view
            class="xiaolanContainer"
            @click="handleToXiaolan"
            v-if="isFixedEntranceHide"
          >
            <img
              src="https://img3.job1001.com/xiaolan/images/xiaolan_blink.png"
              class="xiaolanBlink"
              alt=""
            />
          </view>
        </view>
        <scroll-view scroll-x enable-flex class="filter">
          <view
            class="filter-item"
            :class="{ active: item.isActive }"
            v-for="(item, index) in configList"
            :key="index"
            @click="handleFilter(index)"
          >
            <text>{{ item.label || item.tagTitle }}</text>
            <text
              class="icon icon-arrow-down"
              :class="{ 'icon-arrow-down-light': item.isActive }"
            ></text>
          </view>
        </scroll-view>
      </view>
      <view class="list">
        <SearchItem
          v-for="(item, index) in list"
          :key="index"
          :item="item"
          :keyword="keyword"
          @click="handleToDetail(item)"
        />
        <u-loadmore
          :status="moreLoading"
          :load-text="loadText"
          v-if="list.length || !loaded"
        />
        <Empty
          v-if="loaded && !list.length"
          textColor="#333333"
          text="没有找到您搜索的内容，请换个关键词试试"
          fontSize="28"
          :fontWeight="400"
        />
      </view>
    </view>
    <SelectPopup
      v-for="(item, index) in configList"
      :key="index"
      :show.sync="item.show"
      :options="item.children"
      :title="item.careerTagIds.length > 1 ? item.label : item.tagTitle"
      :value="item.careerTagIds"
      :mode="item.mode"
      valueName="tagId"
      labelName="tagTitle"
      @cancel="handleCancel($event, item, index)"
      @selected="handleSelect($event, item, index)"
      @close="onClose(item)"
    />
  </page-wrap>
</template>

<script>
import SearchItem from "../components/SearchItem.vue";
import SelectPopup from "../components/SelectPopup.vue";
import Empty from "@/components/Empty.vue";

import {
  getSearchList,
  getConfigList,
  libraryPage,
} from "@/api/modules/library";

import ShareMixin from "@/mixins/share";

export default {
  mixins: [ShareMixin],
  components: {
    SearchItem,
    SelectPopup,
    Empty,
  },
  data() {
    return {
      navHeight: getApp().globalData.navHeight,
      libraryPageId: "", // 配置编号
      keyword: "",
      searchIcon: this.$imgBaseSelf + "common/search_3.png",
      careerTagIds: [],
      list: [],
      configList: [],
      pageParams: {
        pageNo: 0,
        pageSize: 10,
      },
      moreLoading: "loadmore",
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "已经到底啦~",
      },
      loaded: false,
      libraryPage: "",
      isChange: false,
      shareTitle: this.$selfName + " - 案例列表",
      scrollTop: 0,
      isFixedEntranceHide: false,
    };
  },
  onLoad(opt) {
    this.libraryPageId = opt.libraryPageId;
    this.sharePath =
      "/pagesSub/library/index?libraryPageId=" + this.libraryPageId;
    this.shareQuery = "libraryPageId=" + this.libraryPageId;

    this.getLibraryPage();
  },
  onReachBottom() {
    this.getData(true);
  },
  onPageScroll(res) {
    this.scrollTop = res.scrollTop;
  },
  methods: {
    getData(isMore) {
      if (this.moreLoading == "loading" || this.moreLoading == "nomore") return;

      let tagIds = [];
      this.configList.forEach((item) => {
        if (item.careerTagIds.length) {
          tagIds.push(item.careerTagIds);
        }
      });
      tagIds = JSON.stringify(tagIds);
      const params = {
        keyword: this.keyword,
        libraryPageId: this.libraryPageId,
        // tagIds: tagIds,
        multiTagIds: tagIds,
        activityTypeCode: "CAREER_CASE",
        pageNo: this.pageParams.pageNo,
        pageSize: this.pageParams.pageSize,
      };

      this.moreLoading = "loading";

      if (!isMore) this.list = [];

      getSearchList(params)
        .then((res) => {
          this.moreLoading = "loadmore";
          if (res.code == 200) {
            let data = res.data;
            if (isMore) {
              this.list.push(...data);
            } else {
              this.list = res.data;
            }
            this.pageParams.pageNo++;
            if (this.pageParams.pageNo > res.pageparam.pages) {
              this.moreLoading = "nomore";
            }
          }
        })
        .finally(() => {
          this.loaded = true;
        });
    },
    getConfigData() {
      if (!this.isExpiration()) {
        let data = uni.getStorageSync("caseConfigData");
        this.handleConfigData(data);
        return;
      }

      const params = {
        libraryPageId: this.libraryPageId,
      };
      getConfigList(params).then((res) => {
        if (res.code == 200) {
          this.saveConfigData(res.data);
          this.handleConfigData(res.data);
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
          });
        }
      });
    },
    getLibraryPage() {
      const params = {
        libraryPageId: this.libraryPageId,
      };
      libraryPage(params)
        .then((res) => {
          if (res.code == 200) {
            this.libraryPage = res.data;
          }
        })
        .finally(() => {
          this.getConfigData();
        });
    },
    handleConfigData(data) {
      this.configList = this.formatConfigData(data.careerTag);
      this.getData();
    },
    formatConfigData(data) {
      if (Array.isArray(data)) {
        data = data.map((element, index) => {
          element.show = false;
          element.isActive = false;
          element.label = "";
          element.careerTagIds = [];
          element.careerTagIdsItems = [];
          if (element.children) {
            element.children.forEach((subElement) => {
              if (
                this.libraryPage &&
                this.libraryPage.careers &&
                this.libraryPage.careers.length
              ) {
                if (this.libraryPage.careers.indexOf(subElement.tagId) > -1) {
                  element.label = subElement.tagTitle;
                  element.careerTagIds.push(subElement.tagId);
                  element.careerTagIdsItems.push(subElement);
                  element.isActive = true;
                }
              }
              if (subElement.children) {
                element.mode = "multilevel";
              }
            });
          }
          return element;
        });
        return data;
      } else {
        return [];
      }
    },
    handleFilter(index) {
      this.configList[index].show = true;
    },
    handleCancel(eventData, configItem, index) {
      this.configList[index].show = false;
      if (!eventData.length) {
        return;
      }
      eventData.forEach((item, index) => {
        configItem.careerTagIds.forEach((_item, _index) => {
          if (item.tagId == _item) {
            configItem.careerTagIds.splice(_index, 1);
            configItem.careerTagIdsItems.splice(_index, 1);
          } else {
            configItem.careerTagIds.push(item.tagId);
            configItem.careerTagIdsItems.push(item);
          }
        });
      });
      // 文字显示处理
      configItem.isActive = configItem.careerTagIds.length > 0;
      this.isChange = true;
      if (configItem.careerTagIds.length > 1) {
        configItem.label =
          configItem.tagTitle + "·" + configItem.careerTagIds.length;
      } else if (configItem.careerTagIds.length == 1) {
        configItem.label = configItem.careerTagIdsItems[0].tagTitle;
      } else {
        configItem.label = "";
      }
    },
    handleSelect(eventData, configItem) {
      if (configItem.careerTagIds) {
        let tagIndex = configItem.careerTagIds.indexOf(eventData.tagId);
        if (tagIndex > -1) {
          configItem.careerTagIds.splice(tagIndex, 1);
          configItem.careerTagIdsItems.splice(tagIndex, 1);
        } else {
          configItem.careerTagIds.push(eventData.tagId);
          configItem.careerTagIdsItems.push(eventData);
        }
      }
      configItem.isActive = configItem.careerTagIds.length > 0;
      this.isChange = true;

      // 文字显示处理
      if (configItem.careerTagIds.length > 1) {
        configItem.label =
          configItem.tagTitle + "·" + configItem.careerTagIds.length;
      } else if (configItem.careerTagIds.length == 1) {
        configItem.label = configItem.careerTagIdsItems[0].tagTitle;
      } else {
        configItem.label = "";
      }
    },
    handleSearch() {
      this.loaded = false;
      this.moreLoading = "loadmore";
      this.pageParams.pageNo = 0;
      this.getData();
    },
    handleToDetail(item) {
      if (item.activityTypeCode == "CAREER_CASE") {
        uni.navigateTo({
          url: "/pagesSub/companyCenter/case/detail?id=" + item.activityIdCode,
        });
      } else if (item.activityTypeCode == "CAREER_REPORT") {
        uni.navigateTo({
          url:
            "/pagesSub/companyCenter/report/detail?id=" + item.activityIdCode,
        });
      }
    },
    onClose(configItem) {
      configItem.show = false;
      if (this.isChange) this.handleSearch();
      this.isChange = false;
    },
    saveConfigData(data) {
      uni.setStorageSync("caseConfigData", data);
      var timestamp = Date.parse(new Date());
      // 加上过期期限
      var expiration = timestamp + 5 * 60 * 1000; //缓存5分钟
      uni.setStorageSync("caseConfigDataExpiration", expiration);
    },
    // 缓存是否过期
    isExpiration() {
      var timestamp = Date.parse(new Date());
      // 缓存中的过期时间
      var expiration = wx.getStorageSync("caseConfigDataExpiration");
      if (expiration) {
        if (timestamp > expiration) {
          return true;
        } else {
          return false;
        }
      }
      return true;
    },
    handleEntranceHide() {
      this.isFixedEntranceHide = true;
    },
    handleToXiaolan() {
      uni.navigateTo({ url: "/pagesSub/elanwBot/index" });
    },
  },
};
</script>

<style lang="scss" scoped>
.library {
  position: relative;
  .library-top {
    position: sticky;
    top: 0;
    background-color: #f7f8fa;
    z-index: 2;
  }

  .search {
    display: flex;
    padding: 16rpx 32rpx;
  }
  .library-u-search {
    flex: 1;
    margin-right: 16rpx;
  }
  @keyframes xiaolanAprear {
    from {
      filter: opacity(0.1);
    }
    to {
      filter: opacity(1);
    }
  }
  .xiaolanBlink {
    width: 80rpx;
    height: 80rpx;
    animation: xiaolanAprear 1s;
  }
  .filter {
    display: flex;
    height: 34rpx;
    padding: 24rpx 0;
    white-space: nowrap;

    &-item {
      margin-right: 52rpx;
      text-align: center;

      &:nth-child(1) {
        margin-left: 32rpx;
      }

      &:last-child {
        padding-right: 32rpx;
      }

      &.active {
        color: #ff6239;
      }

      .icon-arrow-down {
        margin-left: 10rpx;
        width: 16rpx;
        height: 10rpx;
        background-image: url($img-base + "library/filter.png");

        &-light {
          background-image: url($img-base + "library/filter_light.png");
        }
      }
    }
  }

  ::v-deep .nodata {
    margin-top: 100rpx;
  }
}
</style>
